package com.arch.bigdata.hbase.assign;

import org.apache.commons.lang3.RandomUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author pizhihui
 * @date 2024-06-05 09:01
 */
public class AssignmentRunner extends Thread{


    private final ReentrantLock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();


    private final ArrayList<String> queue = new ArrayList<>();

    @Override
    public void run() {
        while (true) {
            // await
            if (queue.isEmpty()) {
                lock.lock();
                try {
                    System.out.println("队列为空,进入无限期等待中...");
                    condition.await();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }

            }

            // process
            try {
                System.out.println("开始处理任务....." + queue.get(0));

                TimeUnit.SECONDS.sleep(30);
            } catch (Exception e) {

            }
            queue.clear();
            System.out.println("结束处理任务.....,清空队列");

        }
    }

    public void queue(String task) {
        lock.lock();
        try {
            queue.add(task);
            if (!queue.isEmpty()) {
                System.out.println("放入队列任务");
                condition.signal();
            }
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        System.out.println("main====启动任务");

        AssignmentRunner assignmentRunner = new AssignmentRunner();
        assignmentRunner.start();

        for (int i = 0; i < 10; i++) {
            TimeUnit.SECONDS.sleep(RandomUtils.nextInt(1,5));
            assignmentRunner.queue("任务1-" + LocalDateTime.now());
        }


    }

}
